﻿
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;

namespace MathService.Tasks
{
    public class Task : ITask
    {
        public event EventHandler Started;
        public event EventHandler Complited;
        public event ExceptionEventHandler<Exception> Error;

        private readonly Action f_Action;

        public DateTime? StartTime { get; private set; }
        public DateTime? CompliteTime { get; private set; }

        public Task(Action action)
        {
            Contract.Requires(!ReferenceEquals(action, null), "action == null");
            if(action == null) throw new ArgumentNullException(nameof(action));
            f_Action = action;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Execute()
        {
            try
            {
                StartTime = DateTime.Now;
                Started.Start(this, EventArgs.Empty);
                f_Action.Invoke();
                CompliteTime = DateTime.Now;
                Complited.Start(this, EventArgs.Empty);
            } catch(Exception error) { Error.ThrowIfUnhandled(this, error); }
        }
    }
}
